package com.med.meddataintegrator.jwt.handle;

import com.med.meddataintegrator.common.basic.response.JsonResult;
import com.med.meddataintegrator.common.basic.response.StatusCode;
import com.med.meddataintegrator.jwt.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Component
@Slf4j
public class RestAuthenticationFailureHandler implements AuthenticationFailureHandler {

    /**
     * 处理认证失败的请求
     * @param request
     * @param response
     * @param exception
     * @throws IOException
     * @throws ServletException
     */


    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

        // 在这里对异常进行分类判断
        log.warn("AuthenticationException: ", exception);
        if (exception instanceof UsernameNotFoundException) {
            // 用户名或密码为空
            log.warn("用户名或密码为空");
            ResultUtil.error(response, JsonResult.fail(StatusCode.USERNAME_OR_PASSWORD_IS_NULL));
            return;
        } else if (exception instanceof BadCredentialsException) {
            // 用户名或密码错误
            log.warn("用户名或密码错误");
            ResultUtil.error(response, JsonResult.fail(StatusCode.USERNAME_OR_PWD_ERROR));
            return;
        }
    }
}
